import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Store } from '@ngxs/store';
import { BookAction } from '../../../store/book';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Navigate } from '@ngxs/router-plugin';
import { RouterSelector } from '../../../store/router/router.selector';
import { ResetForm } from '@ngxs/form-plugin';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.scss'],
})
export class EditComponent implements OnInit {
  validateForm: FormGroup;

  constructor(
      private store: Store,
      private fb: FormBuilder,
      private message: NzMessageService,
  ) {
    this.validateForm = this.fb.group({
      id: [null],
      title: ['', [Validators.required]],
      code: [''],
      description: [''],
      totalCount: [0],
    });
    if ('/book/new' === this.store.selectSnapshot(RouterSelector.url)) {
      this.store.dispatch(new ResetForm({path: 'book.editForm'}));
    }
  }

  ngOnInit(): void {
  }

  submitForm() {
    this.store.dispatch(new BookAction.Save()).subscribe(() => {
      this.message.success(`保存成功`);
      this.store.dispatch(new Navigate(['/book/manage']));
    });
  }
}
